//
//  MQSendProductViewController.m
//  meiquan
//
//  Created by hejingjin on 2017/10/25.
//  Copyright © 2017年 mq. All rights reserved.
//

#import "MQSendProductViewController.h"
#import "MQSendProdcutView.h"
#import "MQChooseCustomViewController.h"
#import "MQChooseProductViewController.h"
#import "MQBaseUserInfoModel.h"
#import "MQCustomInfo.h"
#import "ZHPickView.h"
#import "MQAddressView.h"
#import "MQadviews.h"
#import "MQAdmodels.h"
#import "MQAdDetailViewController.h"
#import "MQPaymentviewViewController.h"
#import "MQOrderListmodel.h"
#import "NSString+Extension.h"
@interface MQSendProductViewController ()<ZHPickViewDelegate,UIPickerViewDataSource, UIPickerViewDelegate,UITextFieldDelegate>
{
    NSInteger _provinceIndex;   // 省份选择 记录
    NSInteger _cityIndex;       // 市选择 记录
    NSInteger _districtIndex;   // 区选择 记录
}


@property(nonatomic,strong)MQSendProdcutView *sendproductview;

@property(nonatomic,strong)UIScrollView *bgview;

@property(nonatomic,strong)MQCustomInfo *cusominfo;
@property(nonatomic,strong)NSArray *addarray;
@property(nonatomic,strong)MQAddressView *adderssview;
@property(nonatomic,strong)ZHPickView *birthdaypic;
@property(nonatomic,strong)ZHPickView *choosepic;

@property(nonatomic,strong)MQadviews *adviews;

@property(nonatomic,strong)MQAdmodels *admodels;




@end

@implementation MQSendProductViewController


-(void)cancelbuttonPressed:(UIButton *)semnder{
    //     [self.view bringSubviewToFront:_adderssview];
    [self.view sendSubviewToBack:_adderssview];
    _provinceIndex = _cityIndex = _districtIndex = 0;
    _adderssview.hidden = YES;
    [_adderssview.pickerviews reloadAllComponents];
}

-(void)makesurebuttonPressed:(UIButton *)sender{
    NSString *address = [NSString stringWithFormat:@"%@ %@ %@", self.addarray[_provinceIndex][@"name"], self.addarray[_provinceIndex][@"list"][_cityIndex][@"name"], self.addarray[_provinceIndex][@"list"][_cityIndex][@"list"][_districtIndex][@"name"]];
    //    NSLog(@"%@",address);
    _adderssview.hidden = YES;
    _sendproductview.songhuodizi.text = address;
//    _custominfoview.adderLabel.text = address;
    [self.view sendSubviewToBack:_adderssview];
}


#pragma mark - UIPicker Delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if(component == 0){
        return self.addarray.count;
    }
    else if (component == 1){
        return [self.addarray[_provinceIndex][@"list"] count];
    }
    else{
        return [self.addarray[_provinceIndex][@"list"][_cityIndex][@"list"] count];
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if(component == 0){
        return self.addarray[row][@"name"];
    }
    else if (component == 1){
        return self.addarray[_provinceIndex][@"list"][row][@"name"];
    }
    else{
        return self.addarray[_provinceIndex][@"list"][_cityIndex][@"list"][row][@"name"];
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    
    return BSTScreenW/3;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if(component == 0){
        _provinceIndex = row;
        _cityIndex = 0;
        _districtIndex = 0;
        [self.adderssview.pickerviews reloadComponent:1];
        [self.adderssview.pickerviews reloadComponent:2];
    }
    else if (component == 1){
        _cityIndex = row;
        _districtIndex = 0;
        [self.adderssview.pickerviews reloadComponent:2];
    }
    else{
        _districtIndex = row;
    }
    // 重置当前选中项
    [self resetPickerSelectRow];
}
-(void)resetPickerSelectRow
{
    [self.adderssview.pickerviews selectRow:_provinceIndex inComponent:0 animated:YES];
    [self.adderssview.pickerviews selectRow:_cityIndex inComponent:1 animated:YES];
    [self.adderssview.pickerviews selectRow:_districtIndex inComponent:2 animated:YES];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel* pickerLabel = (UILabel*)view;
    if (!pickerLabel){
        pickerLabel = [[UILabel alloc] init];
        // Setup label properties - frame, font, colors etc
        //adjustsFontSizeToFitWidth property to YES
        pickerLabel.minimumScaleFactor = 8.;
        pickerLabel.adjustsFontSizeToFitWidth = YES;
        [pickerLabel setTextAlignment:NSTextAlignmentCenter];
        [pickerLabel setFont:[UIFont boldSystemFontOfSize:15]];
    }
    // Fill the label text here
    pickerLabel.text = [self pickerView:pickerView titleForRow:row forComponent:component];
    return pickerLabel;
}

-(void)toobarDonBtnHaveClick:(ZHPickView *)pickView resultString:(NSString *)resultString{
    
    NSInteger index = pickView.tag - 1000;
    if (index == 0) {
        _sendproductview.birthdayTextField.text = resultString;
    }else{
        _sendproductview.buyDate.text = resultString;
    }
//    NSLog(@"%@",resultString);
}



-(void)getaddata{
    
    NSArray *array = @[@"page1",@"@page2",@"page3"];
    int x = arc4random() % 3;
    
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setValue:userinfo.userId forKey:@"userId"];
    [param setValue:array[x] forKey:@"code"];
    
    [MQRequestTools POSTWithMethod:adv_index params:param success:^(id json) {
        
        NSDictionary *dic = [json valueForKey:@"data"];
        _admodels = [MQAdmodels mj_objectWithKeyValues:dic];
        if (_admodels.advId) {
            [_adviews.adimageviews sd_setImageWithURL:[NSURL URLWithString:_admodels.pic] placeholderImage:[UIImage imageNamed:@""]];
            [self.view bringSubviewToFront:_adviews];
            [_bgview setContentSize:CGSizeMake(BSTScreenW, 11 *50 + 20 + 45 + 40 +64 + 70 *Persion)];
        }else{
            _adviews.bst_height = 0;
            _sendproductview.bst_y = MAX_Y(_adviews.frame);
            

        }
        
        
        UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
        [_adviews addGestureRecognizer:tapGesturRecognizer];
        
    } failure:^(NSError *error) {
        
    }];
    
    
}

-(void)tapAction:(UITapGestureRecognizer *)obj{
    NSLog(@"%@",_admodels.url);
    MQAdDetailViewController *advc = [[MQAdDetailViewController alloc] init];
    advc.url = _admodels.url;
     advc.type = _admodels.type;
    [self.navigationController pushViewController:advc animated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.title = @"我要发货";
    
    
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    _provinceIndex = _cityIndex = _districtIndex = 0;
    
    NSString *dataFilePath = [[NSBundle mainBundle] pathForResource:@"region" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:dataFilePath];
    _addarray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    
    _adderssview = [MQAddressView loadaddressviews];
    _adderssview.bst_x = 0;
    _adderssview.bst_height = BSTScreenH * 0.3;
    _adderssview.bst_y = BSTScreenH * 0.7;
    _adderssview.bst_width = BSTScreenW;
    _adderssview.pickerviews.delegate = self;
    _adderssview.pickerviews.dataSource = self;
    [_adderssview.cancelbutton addTarget:self action:@selector(cancelbuttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_adderssview.makesurebutton addTarget:self action:@selector(makesurebuttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    _adderssview.hidden = YES;
    
    [self.view addSubview:_adderssview];
    
    NSDate *currentdate = [NSDate new];
    
    _birthdaypic = [[ZHPickView alloc] initDatePickWithDate:currentdate datePickerMode:UIDatePickerModeDate isHaveNavControler:NO];
    _birthdaypic.tag = 1000;
    _birthdaypic.delegate = self;
    
    _choosepic = [[ZHPickView alloc] initDatePickWithDate:currentdate datePickerMode:UIDatePickerModeDate isHaveNavControler:NO];
    _choosepic.tag = 1001;
    _choosepic.delegate = self;
    
    [self setUpMainInterface];
    
    [self getaddata];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)chooseDateButtonPressed{
    [_choosepic show];
}
-(void)shouhuodizhibuttonpressed{
    _adderssview.hidden = NO;
    [self.view bringSubviewToFront:_adderssview];
}

-(void)birthdatebuttonpressed{
    
    [_birthdaypic show];
}

-(void)setUpMainInterface{
    
    self.view.backgroundColor = BSTColorFromRGB(0xefefef);
    
    
    _adviews = [MQadviews loadadviews];
    _adviews.bst_x = 0;
    _adviews.bst_width = BSTScreenW;
    _adviews.bst_height = 70 *Persion;
    _adviews.bst_y = NAVHEIGHT;
    [self.view addSubview:_adviews];
    
    _sendproductview = [MQSendProdcutView loadmqsendproductview];
    _sendproductview.bst_x = 0;
    _sendproductview.bst_y = MAX_Y(_adviews.frame);
    _sendproductview.bst_width = BSTScreenW;
    _sendproductview.bst_height = 11 * 50 + 20 + 45 + 40;
    
    [_sendproductview.custominfoButton addTarget:self action:@selector(customInfoButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_sendproductview.chooseproductbutton addTarget:self action:@selector(chooseproductbuttonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [_sendproductview.submitButton addTarget:self action:@selector(submitButtonPressed:) forControlEvents:UIControlEventTouchUpInside];

    [_sendproductview.chooseDateButton addTarget:self action:@selector(chooseDateButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    [_sendproductview.songhuodizhibutton addTarget:self action:@selector(shouhuodizhibuttonpressed) forControlEvents:UIControlEventTouchUpInside];
    [_sendproductview.birthdatebutton addTarget:self action:@selector(birthdatebuttonpressed) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_sendproductview];
    
    
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    
    
    if (!userinfo.isAgent) {
        
        _sendproductview.phoneNumberTextField.text = userinfo.username;
        
        
    }
    
    if (_currentcount == 0) {
        
        _sendproductview.priceLabel.text =@"";
        _sendproductview.dailiPriceLabel.text= @"";//        _sendproductview.priceLabel.text =[NSString stringWithFormat:@"¥ %.2f",[_model.price doubleValue]];
      
    }else{
        _sendproductview.chooseproductbutton.enabled = NO;
        _sendproductview.productnamelabel.text = _model.name;
        _sendproductview.buycountTextField.text = [NSString stringWithFormat:@"%ld",_currentcount];
        _sendproductview.buycountTextField.enabled = NO;
      
        _sendproductview.priceLabel.text =[NSString stringWithFormat:@"¥ %.2f",[_model.price doubleValue]];
        //        _sendproductview.priceLabel.text =[NSString stringWithFormat:@"¥ %.2f",[_model.price doubleValue]];
        if (userinfo.isAgent) {
            _sendproductview.dailiPriceLabel.text =[NSString stringWithFormat:@"¥ %.2f",[_model.agentPrice doubleValue]];
        }else{
            _sendproductview.dailiPriceLabel.text =[NSString stringWithFormat:@"¥ %.2f",[_model.price doubleValue]];
        }
//        _sendproductview
    }
    
    UIScrollView *bgview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, BSTScreenW, BSTScreenH)];
    [bgview addSubview:_sendproductview];
    [bgview setContentSize:CGSizeMake(BSTScreenW, 11 *50 + 20 + 45 + 40 +64)];
    _bgview = bgview;
    [self.view addSubview:bgview];
    
}

-(void)submitButtonPressed:(UIButton *)sender{
    
    NSString *buyer = _sendproductview.customNametextfield.text;
    NSString *phone = _sendproductview.phoneNumberTextField.text;
    NSString *productCount = _sendproductview.buycountTextField.text;
    NSString *province;
    NSString *city ;
    NSString *area ;
    
    if (_cusominfo) {
         province= _cusominfo.provinceName;
        city = _cusominfo.cityName;
        area = _cusominfo.areaName;
    }else{
//        self.addarray[_provinceIndex][@"name"], self.addarray[_provinceIndex][@"list"][_cityIndex][@"name"], self.addarray[_provinceIndex][@"list"][_cityIndex][@"list"][_districtIndex][@"name"]
        province =  self.addarray[_provinceIndex][@"name"];
        city = self.addarray[_provinceIndex][@"list"][_cityIndex][@"name"];
        area = self.addarray[_provinceIndex][@"list"][_cityIndex][@"list"][_districtIndex][@"name"];
    }

    NSString *addr = _sendproductview.detailTextField.text;
    
    NSString *buydate = _sendproductview.buyDate.text;
    
    
//    NSString *productcounts = _sendproductview.buycountTextField.text;
    
    if ([NSString isBlankString:buyer]) {
        [iToastUtil displayMsg:@"请输入客户名称"];
        return;
    }
    if ([NSString isBlankString:phone]) {
        [iToastUtil displayMsg:@"请输入购买人电话"];
        return;
    }
    if ([NSString isBlankString:productCount]) {
        [iToastUtil displayMsg:@"请输入购买数量"];
        return;
    }
    if ([NSString isBlankString:province] || [NSString isBlankString:city] || [NSString isBlankString:area]) {
        [iToastUtil displayMsg:@"请选择送货地址"];
        return;
    }
    if ([NSString isBlankString:buydate]) {
        [iToastUtil displayMsg:@"请选择购买日期"];
        return;
    }

    
    
    MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
    [userinfo loadUserinfoFromSadeBox];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:userinfo.userId forKey:@"userId"];
    [param setValue:buydate forKey:@"buyTime"];
    [param setValue:buyer forKey:@"buyer"];
    [param setValue:_model.productId forKey:@"productId"];
    [param setValue:productCount forKey:@"productCount"];
    [param setValue:province forKey:@"province"];
    [param setValue:city forKey:@"city"];
    [param setValue:area forKey:@"area"];
    [param setValue:addr forKey:@"addr"];
    
    [param setValue:phone forKey:@"telephone"];
    
    
    [MQRequestTools POSTWithMethod:orderInfo_save params:param success:^(id json) {
       
        NSDictionary *dic = [json valueForKey:@"data"];
        MQOrderListmodel *model = [MQOrderListmodel mj_objectWithKeyValues:dic];
        
        MQPaymentviewViewController *paymentvc = [[MQPaymentviewViewController alloc] init];
        paymentvc.model = model;
        [self.navigationController pushViewController:paymentvc animated:YES];
//        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    
    
    
}


-(void)chooseproductbuttonPressed:(UIButton *)sender{
    MQChooseProductViewController *chooseproductvc = [[MQChooseProductViewController alloc] init];
    
    [chooseproductvc getcontactWithBolck:^(MQProductListModel *product) {
        _model = product;
        MQBaseUserInfoModel *userinfo = [MQBaseUserInfoModel shareInstant];
        [userinfo loadUserinfoFromSadeBox];
        _sendproductview.productnamelabel.text = _model.name;
        _sendproductview.buycountTextField.text = [NSString stringWithFormat:@"%ld",_currentcount];
//        if (_currentcount > 0) {
                _sendproductview.buycountTextField.enabled = YES;
//        }else{
        
//        }

        _sendproductview.priceLabel.text =[NSString stringWithFormat:@"¥ %.2f",[_model.price doubleValue]];
//        _sendproductview.priceLabel.text =[NSString stringWithFormat:@"¥ %.2f",[_model.price doubleValue]];
        if (userinfo.isAgent) {
            _sendproductview.dailiPriceLabel.text =[NSString stringWithFormat:@"¥ %.2f",[_model.agentPrice doubleValue]];
        }else{
            _sendproductview.dailiPriceLabel.text =[NSString stringWithFormat:@"¥ %.2f",[_model.price doubleValue]];
        }

    }];
    [self.navigationController pushViewController:chooseproductvc animated:YES];
}

-(void)customInfoButtonPressed:(UIButton *)sender{
    
    MQChooseCustomViewController *choosecustomvc = [[MQChooseCustomViewController alloc] init];
    [choosecustomvc getcontactWithBolck:^(MQCustomInfo *contact) {
//        NSLog(@"%@",contact.realName);
        
        _cusominfo = contact;
        _sendproductview.customNametextfield.text = contact.realName;
        _sendproductview.phoneNumberTextField.text = contact.telephone;
        _sendproductview.birthdayTextField.text = contact.birthday;
        _sendproductview.songhuodizi.text = [NSString stringWithFormat:@"%@ %@ %@",contact.provinceName,contact.cityName,contact.areaName];
        
        
    }];
    [self.navigationController pushViewController:choosecustomvc animated:YES];
    
}

@end
